package com.huodongrili.calender;

import java.util.Calendar;

import com.huodongrili.calender.bg.EcOperService;
import com.huodongrili.calender.bg.LoadWeatherTask;
import com.huodongrili.calender.bg.ScheduleService;
import com.huodongrili.calender.data.Constant;
import com.huodongrili.calender.data.DataPreferences;
import com.huodongrili.calender.util.DeviceUtil;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

public class MainPagerActivity extends CalenderFragmentActivity {

	private ViewPager mPager;
	// private Context mContext;
	private Fragment[] fragments;
	private MainFragment mMainFrg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_paper);

		setPageTitleData(false);

		mPager = (ViewPager) findViewById(R.id.pager);

		LinearLayout pane = (LinearLayout) findViewById(R.id.lay_title);

		fragments = new Fragment[2];

		mMainFrg = new MainFragment();

		fragments[0] = mMainFrg;
		fragments[1] = new SettingFragment();

		mPager.setAdapter(new SlideAdapter(getSupportFragmentManager()));

		pane.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Calendar c = Calendar.getInstance();

				int month = c.get(Calendar.MONTH) + 1;
				int year = c.get(Calendar.YEAR);
				int day = c.get(Calendar.DAY_OF_MONTH);
				mMainFrg.backToToday(year, month);
				mMainFrg.changedEventData(0, year, month, day);
			}
		});

		new LoadWeatherTask(getApplicationContext()).execute();

		DataPreferences dpf = DataPreferences
				.getInstance(getApplicationContext());
		if (!dpf.isWifiSync()) {
			startService(new Intent(this, EcOperService.class));
		}else{
			
			if(!DeviceUtil.isServiceRunning(getApplicationContext(), Constant.BG_SERVICE_NAME)){
				startService(new Intent(this, ScheduleService.class));
			}
			
		}

	}

	private class SlideAdapter extends FragmentPagerAdapter {

		public SlideAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			return fragments[position];
		}

		@Override
		public int getCount() {
			return fragments.length;
		}

	}
}
